package com.cv.framework.web.core.handler;

import cn.hutool.core.util.ObjUtil;
import com.cv.framework.common.pojo.Result;
import com.cv.framework.web.core.utils.WebFrameworkUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 全局响应处理器
 *
 * @author Charles_XDXD
 */
@ControllerAdvice
public class GlobalResponseBodyHandler implements ResponseBodyAdvice {

    @Override
    @SuppressWarnings("NullableProblems")
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (ObjUtil.isEmpty(returnType)) {
            return false;
        }

        return Objects.requireNonNull(returnType.getMethod()).getReturnType().equals(Result.class);
    }

    @Override
    @SuppressWarnings("NullableProblems")
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 记录 Controller 结果
        WebFrameworkUtils.setResult(((ServletServerHttpRequest) request).getServletRequest(), (Result<?>) body);
        return body;
    }

}
